﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System.Threading.Workers
{
  public abstract class EventWorker : Worker
  {
    #region Fields
    private AutoResetEvent _waitHandle = new AutoResetEvent(false);
    #endregion

    #region Constructors
    public EventWorker(string name) : base(name)
    {

    }
    #endregion
    #region Methods
    /// <summary>
    /// Triggers the background thread to start work
    /// </summary>
    /// <returns>False if the worker is busy</returns>
    public bool DoWork()
    {
      return DoWork(false);
    }

    /// <summary>
    /// Triggers the background thread to start work
    /// </summary>
    /// <param name="wait">True to block until the worker thread is not busy</param>
    /// <returns>False if the worker is busy.</returns>
    public bool DoWork(bool wait)
    {
      if (IsBusy)
      {
        if (wait)
          _waitHandle.WaitOne();
        else
          return false;
      }

      (WaitHandle as AutoResetEvent).Set();
      return true;
    }
    #endregion

    #region Overrides
    protected override void OnWorkPerformed(WorkPerformedEventArgs e)
    {
      _waitHandle.Set();
      base.OnWorkPerformed(e);
    }
    #endregion
  }
}
